package baoxin.com.robotcoach;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class ScanActivity extends BLEActivity implements View.OnClickListener {

    final static int REQUEST_COARSE_LOCATION = 101;

    private BluetoothAdapter bluetoothAdapter;

    protected Handler handler = new Handler();

    private static final long SCAN_PERIOD = 10000;

    private DevListAdapter devListAdapter;

    Button startScan;
    Button stopScan;
    ListView lv_bleList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_scan);
        super.onCreate(savedInstanceState);

        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
        }
        checkBluetoothPermission();

        lv_bleList = findViewById(R.id.lv_bleList);
        startScan = findViewById(R.id.start_scan);
        stopScan = findViewById(R.id.stop_scan);
        startScan.setOnClickListener(this);
        stopScan.setOnClickListener(this);

        devListAdapter = new DevListAdapter();
        lv_bleList.setAdapter(devListAdapter);

        lv_bleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                BluetoothDevice device1 = devListAdapter.getItem(position);
                String mDeviceAddress = device1.getAddress();

                if (mBluetoothLeService != null) {

                    mBluetoothLeService.connect(mDeviceAddress);

                }

            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_scan:
                devListAdapter.clear();
                devListAdapter.notifyDataSetChanged();
                scanLeDevice(true);
                break;
            case R.id.stop_scan:
                scanLeDevice(false);
                break;
        }
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    bluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);


            bluetoothAdapter.startLeScan(mLeScanCallback);
        } else {

            bluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    devListAdapter.addDevice(device);
                    devListAdapter.notifyDataSetChanged();
                }
            });
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        scanLeDevice(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        scanLeDevice(false);
    }

    class DevListAdapter extends BaseAdapter {
        private ViewHolder viewHolder;
        private List<BluetoothDevice> devices;

        public DevListAdapter() {
            devices = new ArrayList<>();
        }

        public void addDevice(BluetoothDevice device) {
            if (!devices.contains(device)) {
                devices.add(device);
            }
        }

        public void clear() {
            devices.clear();
        }

        @Override
        public int getCount() {
            return devices.size();
        }

        @Override
        public BluetoothDevice getItem(int position) {
            return devices.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(ScanActivity.this).inflate(R.layout.listitem_device, null);
                viewHolder = new ViewHolder();
                viewHolder.devName = convertView.findViewById(R.id.device_name);
                viewHolder.devAddress = convertView.findViewById(R.id.device_address);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            BluetoothDevice device = devices.get(position);
            String devName = device.getName();
            if (devName != null && devName.length() > 0) {
                viewHolder.devName.setText(devName);
            } else {
                viewHolder.devName.setText("未知设备");
            }
            viewHolder.devAddress.setText(device.getAddress());
            return convertView;
        }
    }

    class ViewHolder {
        TextView devName, devAddress;
    }


    private void checkBluetoothPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            //校验是否已具有模糊定位权限
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_COARSE_LOCATION);
            } else {
                //具有权限

            }
        } else {
            //系统不高于6.0直接执行

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_COARSE_LOCATION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    Toast.makeText(this, "程序正常工作需要位置权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

}
